// pages/merchant/coupon-verification/index.js
const apiService = require('../../../utils/api.js');

Page({
  data: {
    // 核销统计
    verificationStats: {
      today: 0,
      total: 0,
      meituan: 0,
      douyin: 0
    },
    
    // 选中的平台
    selectedPlatform: 'meituan',
    
    // 券码输入
    couponCode: '',
    inputFocus: false,
    
    // 核销记录
    verificationRecords: [],
    
    // 加载状态
    isLoading: false,
    
    // 结果弹窗
    showResultModal: false,
    verificationResult: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('券码核销页面加载', options);
    this.loadVerificationRecords();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadVerificationRecords();
  },

  /**
   * 加载核销记录
   */
  async loadVerificationRecords() {
    try {
      // 模拟核销记录数据
      const mockRecords = [
        {
          id: 'record_001',
          platform: 'meituan',
          platformName: '美团',
          platformIcon: '🍔',
          couponCode: 'MT20240125001',
          amount: 50,
          status: 'success',
          statusText: '核销成功',
          statusClass: 'success',
          verifyTime: '2024-01-25 14:30:25'
        },
        {
          id: 'record_002',
          platform: 'douyin',
          platformName: '抖音',
          platformIcon: '🎵',
          couponCode: 'DY20240125002',
          amount: 30,
          status: 'success',
          statusText: '核销成功',
          statusClass: 'success',
          verifyTime: '2024-01-25 15:45:12'
        },
        {
          id: 'record_003',
          platform: 'meituan',
          platformName: '美团',
          platformIcon: '🍔',
          couponCode: 'MT20240125003',
          amount: 0,
          status: 'failed',
          statusText: '核销失败',
          statusClass: 'failed',
          verifyTime: '2024-01-25 16:20:08'
        }
      ];

      // 计算统计数据
      const stats = {
        today: mockRecords.filter(r => r.verifyTime.includes('2024-01-25')).length,
        total: mockRecords.length,
        meituan: mockRecords.filter(r => r.platform === 'meituan').length,
        douyin: mockRecords.filter(r => r.platform === 'douyin').length
      };

      this.setData({
        verificationRecords: mockRecords,
        verificationStats: stats
      });

      console.log('核销记录加载成功:', mockRecords);
      
    } catch (error) {
      console.error('加载核销记录失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  /**
   * 选择平台
   */
  onSelectPlatform(e) {
    const platform = e.currentTarget.dataset.platform;
    this.setData({
      selectedPlatform: platform,
      couponCode: '' // 清空券码
    });
  },

  /**
   * 券码输入
   */
  onCouponCodeInput(e) {
    this.setData({
      couponCode: e.detail.value.trim()
    });
  },

  /**
   * 扫码
   */
  onScanCode() {
    wx.scanCode({
      success: (res) => {
        console.log('扫码结果:', res);
        this.setData({
          couponCode: res.result
        });
      },
      fail: (error) => {
        console.error('扫码失败:', error);
        wx.showToast({
          title: '扫码失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 核销券码
   */
  async onVerifyCoupon() {
    const { couponCode, selectedPlatform } = this.data;
    
    if (!couponCode.trim()) {
      wx.showToast({
        title: '请输入券码',
        icon: 'none'
      });
      return;
    }

    this.setData({ isLoading: true });

    try {
      // 模拟券码验证，实际项目中应该调用API
      const verificationResult = await this.mockVerifyCoupon(couponCode, selectedPlatform);
      
      this.setData({
        verificationResult,
        showResultModal: true,
        couponCode: '' // 清空输入框
      });

      // 如果核销成功，更新记录
      if (verificationResult.success) {
        this.addVerificationRecord(verificationResult);
      }
      
    } catch (error) {
      console.error('核销券码失败:', error);
      wx.showToast({
        title: '核销失败',
        icon: 'none'
      });
    } finally {
      this.setData({ isLoading: false });
    }
  },

  /**
   * 模拟券码验证
   */
  async mockVerifyCoupon(couponCode, platform) {
    // 模拟网络请求延迟
    await new Promise(resolve => setTimeout(resolve, 1500));

    // 模拟验证逻辑
    const platformInfo = {
      meituan: { name: '美团', icon: '🍔' },
      douyin: { name: '抖音', icon: '🎵' }
    };

    // 模拟验证结果（80%成功率）
    const isSuccess = Math.random() > 0.2;
    
    if (isSuccess) {
      return {
        success: true,
        couponCode,
        platform,
        platformName: platformInfo[platform].name,
        platformIcon: platformInfo[platform].icon,
        amount: Math.floor(Math.random() * 100) + 10, // 10-110元
        expireTime: '2024-12-31 23:59:59',
        message: '核销成功'
      };
    } else {
      const errorMessages = [
        '券码已过期',
        '券码不存在',
        '券码已被使用',
        '券码格式错误',
        '平台验证失败'
      ];
      
      return {
        success: false,
        couponCode,
        platform,
        platformName: platformInfo[platform].name,
        platformIcon: platformInfo[platform].icon,
        amount: 0,
        message: errorMessages[Math.floor(Math.random() * errorMessages.length)]
      };
    }
  },

  /**
   * 添加核销记录
   */
  addVerificationRecord(result) {
    const newRecord = {
      id: 'record_' + Date.now(),
      platform: result.platform,
      platformName: result.platformName,
      platformIcon: result.platformIcon,
      couponCode: result.couponCode,
      amount: result.amount,
      status: result.success ? 'success' : 'failed',
      statusText: result.success ? '核销成功' : '核销失败',
      statusClass: result.success ? 'success' : 'failed',
      verifyTime: this.formatTime(new Date())
    };

    const records = [newRecord, ...this.data.verificationRecords];
    
    // 更新统计数据
    const stats = {
      today: records.filter(r => r.verifyTime.includes(this.getToday())).length,
      total: records.length,
      meituan: records.filter(r => r.platform === 'meituan').length,
      douyin: records.filter(r => r.platform === 'douyin').length
    };

    this.setData({
      verificationRecords: records,
      verificationStats: stats
    });
  },

  /**
   * 关闭结果弹窗
   */
  onCloseResultModal() {
    this.setData({ showResultModal: false });
  },

  /**
   * 格式化时间
   */
  formatTime(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },

  /**
   * 获取今天日期
   */
  getToday() {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    return `${year}-${month}-${day}`;
  },

  /**
   * 防止弹窗滚动穿透
   */
  preventTouchMove() {
    return false;
  }
});
